public with sharing class AddCityListMSRControl
{

    public String msg{get;set;}
    public id HCPEducationRecordTypeId{get;set;}
  //get url id
    public String UrlId
    {
        get
        {        
            return System.currentPageReference().getParameters().get('id');     
        }  
        set;
    }    
    
    public List<JoinPeople__c>  HaveJPList = [Select id,OwnerId,User__c From JoinPeople__c Where CityNameList__c =: UrlId];  
    
    public List<AddSubordinateItemControl> SubordinateList{
        get{     
                if(SubordinateList == null){
                    SubordinateList = new List<AddSubordinateItemControl>();
                }      
       
                return SubordinateList;                                                                     
        }
        set;
    }

    public AddCityListMSRControl()
    {
        List<User> subList = [Select Name,UserRoleId,Title__c From User Where Id =:UserInfo.getUserId() and IsActive=:true];
        HCPEducationRecordTypeId=[select id,name,sobjecttype,developername from recordtype where sobjecttype=:'callplan__c' and developername=:'HCPEducation'].id;
        if(subList.size() > 0){
            Boolean haveflag = false;
            User currentRole = subList.get(0);
            
            List<User> u = [Select Id,UserRoleId,Title__c From User Where Title__c = 'Sales Rep' and FunctionDepartment__c ='Medical Sales' and IsActive=:true];
            if(u.size() > 0)
            {
                if(currentRole.UserRoleId != u.get(0).UserRoleId){
                    List<UserRole> sur1 = [Select Id,Name From UserRole Where ParentRoleId =: currentRole.UserRoleId];
                    List<User> secondLine = new List<User>();                   
                    for(UserRole urole:sur1){
                        List<User> sub1 = [Select Id,Name,UserRoleId,Title__c  From User Where UserRoleId  =: urole.Id and IsActive=:true and FunctionDepartment__c='Medical Sales'];                                                           
                        for(User user:sub1){
                            haveflag = true;
                            secondLine.add(user);
                            SubordinateList.add(new AddSubordinateItemControl(user,urole));
                        }
                    }
                    Boolean loopflag = true; 
                    Boolean firsttime = true;                   
                    List<User> NextUser = new List<User>();
                    List<User> ComUser = new List<User>();
                    
                    while(loopflag){
                        if(secondLine.size() > 0)
                        {                                                                 
                            List<UserRole> NextRole = [Select Id,Name From UserRole Where ParentRoleId =: secondLine.get(0).UserRoleId];
                            List<ID> NextRoleId = new List<ID>();
                            for(UserRole ur : NextRole ){
                                NextRoleId.add(ur.Id);
                            }
                            if(NextRole.size() <= 0){
                                break;
                            }                                                                            
                            NextUser = [Select Id,Name,UserRoleId,Title__c From User Where UserRoleId  in: NextRoleId and IsActive=:true and FunctionDepartment__c='Medical Sales'];
                            for(User add : NextUser)
                            {
                                List<UserRole> curRole = [Select Id,Name From UserRole Where Id =: add.UserRoleId]; 
                                AddSubordinateItemControl sub = new AddSubordinateItemControl(add,curRole.get(0));
                                SubordinateList.add(sub);
                                secondLine = NextUser.clone();                                
                            }
                            if(NextUser.get(0).Title__c == 'Sales Rep')
                            {
                                break;
                            }                                               
                         }                                          
                    }
 
            }
        }      
        

            for(AddSubordinateItemControl asi :SubordinateList)
            {
                for(JoinPeople__c jp : HaveJPList)
                {
                    if(asi.subUser.id == jp.User__c)
                    {
                        asi.IsCheck = true;
                    }
                }
            }
        }        
         
    }  
    public PageReference Save()
    {
        id hcpeduid=[select id,RegionNameList__r.HCPEducation__c from CityNameList__c where id =:urlid limit 1].RegionNameList__r.HCPEducation__c;
        hcpeducation__c hcpedu=[select id,date__c,name,HCPeducationactivitytype__c,time__c,Messaging__c  from hcpeducation__c where id =:hcpeduid limit 1];
        recordtype HCPEducationRecordType=[select id,sobjecttype,developername from recordtype where sobjecttype=:'event' and developername=:'nationalHCP' limit 1];
        List<JoinPeople__c> DJPlist = new List<JoinPeople__c>();
        list<event> insertEvent=new list<event>();
        set<Date> SortDate=new set<date>();
        set<id> ownerId=new set<id>();
        list<MonthlyCallPlan__c> MCPList=new list<monthlycallplan__c>();
        if(hcpedu!=null){
            MCPList=[select id,ownerid from MonthlyCallPlan__c where PlanYear__c =:string.valueof(hcpedu.date__c.year()) and MonthNo__c =:string.valueof(hcpedu.date__c.month()) ];
        }
        Map<id,MonthlyCallPlan__c> MCPMap=new map<id,MonthlyCallPlan__c>();
        for(MonthlyCallPlan__c mcp:MCPList){
            mcpmap.put(mcp.ownerid,mcp);
        }
        
        if(SubordinateList != null)
        {                       
            for(AddSubordinateItemControl item: SubordinateList)
            {
                Boolean haveflag = false;
                if(item.IsCheck == true)
                {
                   JoinPeople__c joinPeople = new JoinPeople__c();
                   joinPeople.CityNameList__c = UrlId;
                   joinPeople.User__c = item.subUser.Id;
                   joinPeople.OwnerId = item.subUser.Id;
                   
                   MonthlyCallPlan__c MCP=new MonthlyCallPlan__c();
                       if(MCPmap.containskey(item.subUser.id)){
                           mcp=mcpmap.get(item.subuser.id);
                       }else{
                           mcp=new MonthlyCallPlan__c(
                               ownerid=item.subUser.id,
                               name=item.subuser.name+' '+hcpedu.date__c.year()+'年'+hcpedu.date__c.month()+'月拜访计划',
                               PlanYear__c=string.valueof(hcpedu.date__c.year()),
                               PlanMonth__c=string.valueof(hcpedu.date__c.month())+'月'
                           );
                           insert mcp;
                       }
                       CallPlan__c cp=new CallPlan__c();
                       cp.name=hcpedu.HCPeducationactivitytype__c+':'+hcpedu.name;
                       cp.recordtypeid=HCPEducationRecordTypeId;
                       cp.plantype__c='计划内';
                       cp.CallPurpose__c='其他';
                       cp.Callplandate__c=hcpedu.date__c;
                       time t;
                       datetime dt;
                       if(hcpedu.time__c == '上午'){
                                t= time.newInstance(9,0,0,0);
                        }
                        else if (hcpedu.time__c == '下午'){
                                t = time.newInstance(14,0,0,0);
                        }
                        dt=datetime.newinstance(hcpedu.date__c,t);
                        cp.calldate__c=dt;
                        cp.callworkingtype__c='全国医护人员教育活动';
                        cp.monthly_call_plan__c=mcp.id;
                        cp.callmessage__c=hcpedu.messaging__c;
                        cp.activityid__c=hcpedu.id;
                        cp.UniqueId__c=''+hcpedu.id+item.subuser.id;
                        
                        upsert cp uniqueId__c;
                           
                        Event e = new Event(Subject='全国医护人员教育活动', 
                                                    WhatId=hcpedu.id,
                                                    recordtypeid=HCPEducationRecordType.id,
                                                    ownerid=item.subUser.id,
                                                    StartDateTime=datetime.newInstancegmt(hcpedu.date__c.year(),hcpedu.date__c.month(),hcpedu.date__c.day(), 0, 0, 0),
                                                    EndDateTime=datetime.newInstancegmt(hcpedu.date__c.year(),hcpedu.date__c.month(),hcpedu.date__c.day(), 0, 30, 0),
                                                    IsReminderSet = false,
                                                    eventDate__c=hcpedu.date__c,
                                                    hospitalname__c=hcpedu.name
                                                     );
                         insertEvent.add(e);
                         sortDate.add(hcpedu.date__c);
                         ownerId.add(item.subUser.id);

                   for(JoinPeople__c jnPeople: HaveJPList)
                   {
                       if(jnPeople.User__c == item.subUser.Id)
                       {
                           haveflag = true;
                       }
                   }
                   if(haveflag == false){
                       insert joinPeople;
                   }                                                                    
                }
                else{
                   for(JoinPeople__c jnPeople: HaveJPList)
                   {
                       if(jnPeople.User__c == item.subUser.Id)
                       {
                           DJPlist.add(jnPeople);
                       }
                   }
                }
            }
            if(insertevent.size()>0){
                insert insertevent;
                CalendarSorter.sort(sortDate,Ownerid);
            }
            if(DJPlist.size()>0)
                delete DJPlist;
            pageReference pr = new pageReference('/'+ UrlId);     
            pr.setredirect(true);      
            return pr;
        }
    
        return null;
    }
    
     public PageReference Cancel()
    {
            //go back to region list page
            pageReference pr = new pageReference('/'+ UrlId);     
            pr.setredirect(true);      
            return pr;
    }   
 
    static testMethod void runtest() {



        Profile p  = [select id from profile where name = 'Area/District Sales Manager - Medical'];
        Profile p1  = [select id from profile where name = 'System Administrator' or name =: '系统管理员'];
        UserRole ur = [select id From UserRole where name = 'SOC1 GZ ASM/DSM-M1'];
        UserRole ur1 = [select id From UserRole where name = 'SOC1 HD Sales Supervisor-M1'];
        
        User u1 = new User (alias = 'stanadt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8', 
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='standaaduser@testorg1.com');
        insert u1;    
        
        User u = new User (alias = 'stafndt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8', UserRoleId = ur1.id,
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p1.id, 
                timezonesidkey = 'America/Los_Angeles', username='standargduser@testorg1.com');
        insert u;   

        User u2 = new User (alias = 'statndt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8', UserRoleId = ur.id,
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Supervisor',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='starduaser@testorg1.com');
        insert u2; 
    System.runas(u){
        AddCityListMSRControl testCase=new AddCityListMSRControl();
        System.assert(testCase.UrlId == null);
        System.assert(testCase.SubordinateList != null);       
               

        HCPEducation__c nhcpe = new HCPEducation__c();
        nhcpe.Name = 'a';
        nhcpe.date__c = date.Today().addDays(3);
        nhcpe.place__c = 'a';
        nhcpe.ownerid = u.id;
        insert nhcpe;
        
        RegionNameList__c rnl = new RegionNameList__c();       
        rnl.name = 'a';
        rnl.HCPEducation__c = nhcpe.Id;
        rnl.ownerid = u2.id;
        insert rnl;
                
            
        CityNameList__c cnl = new CityNameList__c();
        cnl.RegionNameList__c = rnl.Id;
        cnl.Name = 'a';
        cnl.ownerid = u2.id;
        insert cnl;
        
        test.setCurrentPageReference(Page.AddCityListMSR);
        System.currentPageReference().getParameters().put('id', cnl.Id); 
             
        AddSubordinateItemControl add = new AddSubordinateItemControl();
        add.IsCheck = true;
        add.subUser = u1;
        testCase.SubordinateList.add(add);
       // testCase.Save();
        testCase.Cancel();
        }    
     }
}